package com.company.cloud.oss.modules.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.utils.ImageNameUtils;
import com.company.cloud.common.utils.IpUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.oss.config.OssConfig;
import com.company.cloud.oss.modules.app.service.OssStoreService;
import com.company.cloud.oss.modules.base.entity.OssStoreInfo;
import com.company.cloud.oss.modules.base.service.OssStoreInfoService;
import com.company.cloud.oss.modules.cloud.CloudStorageService;
import com.company.cloud.oss.modules.cloud.OSSFactory;
import com.company.cloud.oss.modules.cloud.models.ImgInfoModel;
import com.company.cloud.oss.modules.cloud.models.ImgProcess2SaveModel;
import com.company.cloud.oss.utils.AliYunOssCallbackModel;
import com.company.common.server.config.id.OssIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OssStoreServiceImpl implements OssStoreService {

    @Autowired
    private OssStoreInfoService ossStoreInfoService;
    @Autowired
    private OssConfig ossConfig;


    @Override
    public OssStoreInfo add(AliYunOssCallbackModel callbackModel) {
        String fileName= this.processImg(callbackModel);
		OssStoreInfo entity=new OssStoreInfo();
		entity.setFileNo(OssIdUtil.getFileNo());
		entity.setCompanyNo(callbackModel.getCompanyNo());
		entity.setFileName(fileName);
		entity.setFileUrl(ossConfig.getFileUrl(fileName));
		entity.setFileFormat(callbackModel.getFormat());
		entity.setRowsState(BaseConstant.EnabledEnum.ENABLED.getCode());
		entity.setCman(StringUtils.isEmpty(callbackModel.getUserId())?-1:Integer.parseInt(callbackModel.getUserId()));
		entity.setCdt(LocalDateTime.now());
		entity.setCip(IpUtils.getOpIp());
		entity.setEman(entity.getCman());
		entity.setEdt(entity.getCdt());
		entity.setEip(entity.getCip());
		ossStoreInfoService.save(entity);
        return entity;
    }

    /**处理图片*/
    private String processImg(AliYunOssCallbackModel callbackModel){
        if(StrUtil.isEmpty(callbackModel.getMimeType()) ||
                !callbackModel.getMimeType().toLowerCase().startsWith("image")){
            return ImageNameUtils.getImgName2Param(callbackModel.getFileName(),0,0,null);
        }
        CloudStorageService cloudStorageService= OSSFactory.build(ossConfig);
        int w=0; //宽
        int h=0; //高
        String f=""; //格式
        if(callbackModel.getWidth()<=0 || callbackModel.getHeight()<=0 || StrUtil.isEmpty(callbackModel.getFormat())){
            String imgUrl=ossConfig.getFileUrl(callbackModel.getFileName());
            try {
                ImgInfoModel imgInfo = cloudStorageService.getImgInfo(imgUrl);
                w=imgInfo.getImgWidth();
                h=imgInfo.getImgHeight();
                f=imgInfo.getImgFormat();
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            w=callbackModel.getWidth();
            h= callbackModel.getHeight();
            f=callbackModel.getFormat();
        }

        //check
        if(w<=0||h<=0||StrUtil.isEmpty(f)){
            return ImageNameUtils.getImgName2Param(callbackModel.getFileName(),w,h,null);
        }

        List<Integer> resizeWidthList=new ArrayList<Integer>();
        if(StrUtil.isNotEmpty(callbackModel.getResizeWidth())){
            resizeWidthList= StrSplitUtils.parse2list(callbackModel.getResizeWidth(),Integer.class);
        }

        Map<Integer, Integer> imgParamWH=new HashMap<>();
        for(Integer resizeWidth:resizeWidthList){
            int resizeHeight=this.getResizeHeight(h,w,resizeWidth);
            String styleType;
            if(callbackModel.getQuality()>0 && callbackModel.getQuality()<100){
                styleType=StrUtil.format("image/resize,w_{}/quality,q_{}/format,{}",resizeWidth,callbackModel.getQuality(),f);
            }else{
                styleType=StrUtil.format("image/resize,w_{}/format,{}",resizeWidth,f);
            }
            ImgProcess2SaveModel imgProcess2SaveModel=cloudStorageService.process2SaveAs(styleType,
                    callbackModel.getFileName(),
                    ImageNameUtils.getSaveImageName(callbackModel.getFileName(),resizeWidth,resizeHeight)
            );
            if(imgProcess2SaveModel!=null){
                imgParamWH.put(resizeWidth,resizeHeight);
            }
        }
        return ImageNameUtils.getImgName2Param(callbackModel.getFileName(),w,h,imgParamWH);
    }



    /**处理图片，收缩后高度（px）*/
    private int getResizeHeight(int h ,int w,int resizeWidth){
        float resizeHeight=(float)resizeWidth/w * h;
        return Math.round(resizeHeight);
    }





}
